package com.wiz.weixin.manager;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wiz.weixin.common.TencentConstant;
import com.wiz.weixin.util.TencentUtil;
import com.wiz.weixin.vo.ActionInfo;
import com.wiz.weixin.vo.CodeTicket;

/**
 * 二维码相关
 * @author Administrator
 *
 */
@Service("codeManager")
public class CodeManager implements TencentConstant{
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	@Resource
	private WxAccessManager wxAccessManager;
	
	private final String OBTAIN_TICKET_URL="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";
	
	private final String QR_SCENE="QR_SCENE";//临时二维码
	private final String QR_LIMIT_SCENE="QR_LIMIT_SCENE";//永久二维码
	private final String QR_LIMIT_STR_SCENE="QR_LIMIT_STR_SCENE";//永久的字符串参数二维码
	
	public JSONObject getTicket(int type,String sceneStr,String sceneId) throws JSONException{
		String url = OBTAIN_TICKET_URL.replace("TOKEN", WxAccessManager.getTencent_wx_token());
		
		Map<String,Object>scene = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(sceneId)){
			scene.put("scene_id", sceneId);
		}
		if(StringUtils.isNotBlank(sceneStr)){
			scene.put("scene_str", sceneStr);
		}
		ActionInfo actionInfo = new ActionInfo(scene);
		String actionName = null;
		if(type == 1){
			actionName = QR_SCENE;
		}else if(type == 2){
			actionName = QR_LIMIT_SCENE;
		}else if(type == 3){
			actionName = QR_LIMIT_STR_SCENE;
		}
//		log.info("qrcode url="+url);
		CodeTicket codeTicket = new CodeTicket(actionName, actionInfo);
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(codeTicket);
//		log.info("codeTicket json="+jsonObject);
		String response = TencentUtil.httpsRequest(url, "POST", jsonObject.toString());
//		log.info("QRCode get from Tencent response="+response);
		org.json.JSONObject responseJson = new org.json.JSONObject(response);
		if(response.indexOf("errcode") >=0){
			if(responseJson.getInt("errcode") == 40001){
				wxAccessManager.resetTempTask();
			}
		}
		return responseJson;
	}
}
